
//
//  FMDBCityDataTool.m
//  Shengzhuli
//
//  Created by 卡忙科技 on 16/8/4.
//  Copyright © 2016年 kamangkeji. All rights reserved.
//

#import "FMDBCityDataTool.h"
#import <FMDB.h>
#import "CityGroupModel.h"
#import "CityModel.h"

#define cityPath [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject]stringByAppendingPathComponent:@"cities.sqlite"]

@interface FMDBCityDataTool()

@property (nonatomic,strong) FMDatabaseQueue *dbQueue;

@end
@implementation FMDBCityDataTool

static FMDBCityDataTool *_tool;
+ (instancetype)shareTool
{
    if (!_tool) {
        _tool = [[FMDBCityDataTool alloc]init];
    }
    return _tool;
}
- (instancetype)init
{
    if (self = [super init]) {
        //[self dropCityTable];
        [self createCityTable];
    }
    return self;
}

- (void)addCity:(NSArray *)cities
{
    [self.dbQueue inDatabase:^(FMDatabase *db) {
        for (CityGroupModel *cityModel in cities) {
            for (CityModel *model in cityModel.cities) {
                [db executeUpdate:@"INSERT INTO t_city (id, name, firstLetter, parentId) VALUES (?, ?, ?, ?);", @(model.ID),model.name,model.firstLetter,model.parentId];
            }
        }
    }];
}

- (NSMutableArray *)selectCityWithText:(NSString *)keyword
{
    if(keyword.length == 0) return nil;
    NSMutableDictionary *cityDict = [NSMutableDictionary dictionary];
    [self.dbQueue inDatabase:^(FMDatabase *db) {
        NSString *sql = [NSString stringWithFormat:@"SELECT * FROM t_city WHERE name LIKE '%%%@%%' ORDER BY rowid ASC",keyword];
        FMResultSet *rs = [db executeQuery:sql];
        while ([rs next]) {
            CityModel *city = [[CityModel alloc]init];
            city.ID = [rs intForColumn:@"id"];
            city.name = [rs stringForColumn:@"name"];
            city.firstLetter = [rs stringForColumn:@"firstLetter"];
            city.parentId = [rs stringForColumn:@"parentId"];
            if (city.name) {
                NSMutableArray *list = cityDict[city.firstLetter];
                if (!list) {
                    list = [NSMutableArray array];
                    cityDict[city.firstLetter] = list;
                }
                [list addObject:city];
            }
        }
        [rs close];
    }];
    NSMutableArray *list = [NSMutableArray array];
    NSArray *keys = [[cityDict allKeys] sortedArrayUsingSelector:@selector(compare:)];
    for (NSInteger i=0;i<keys.count;i++) {
        CityGroupModel *group = [[CityGroupModel alloc]init];
        group.firstLeter = keys[i];
        group.cities = cityDict[keys[i]];
        [list addObject:group];
    }
    return list;
}

- (void)createCityTable
{
    [self.dbQueue inDatabase:^(FMDatabase *db) {
        BOOL success = [db executeUpdate:@"CREATE TABLE IF NOT EXISTS t_city (id integer PRIMARY KEY, name text, firstLetter text, parentId text);"];
        NSLog(@"%@",cityPath);
        if (success) {
            NSLog(@"创表成功");
        }else{
            NSLog(@"创表失败");
        }
    }];
}
- (CityModel *)selectCityModel:(NSString *)keyword
{
    if(keyword.length == 0) return nil;
    CityModel *city = [[CityModel alloc]init];
    [self.dbQueue inDatabase:^(FMDatabase *db) {
        FMResultSet *rs = [db executeQuery:@"SELECT * FROM t_city WHERE name = ?",keyword];
        while ([rs next]) {
            city.ID = [rs intForColumn:@"id"];
            city.name = [rs stringForColumn:@"name"];
            city.firstLetter = [rs stringForColumn:@"firstLetter"];
            city.parentId = [rs stringForColumn:@"parentId"];
        }
        [rs close];
    }];
    return city;
}
- (BOOL)isTableOK:(NSString *)tableName
{
    __block BOOL isExist = NO;
    [self.dbQueue inDatabase:^(FMDatabase *db) {
        NSString *sql = [NSString stringWithFormat:@"SELECT * FROM t_city"];
        FMResultSet *rs = [db executeQuery:sql];
        while ([rs next]) {
            isExist = YES;
        }
    }];
    return isExist;
}
- (void)dropCityTable
{
    [self.dbQueue inDatabase:^(FMDatabase *db) {
        [db executeUpdate:@"drop table if exists t_city;"];
    }];
}
- (FMDatabaseQueue *)dbQueue
{
    if (!_dbQueue) {
        _dbQueue = [FMDatabaseQueue databaseQueueWithPath:cityPath];
    }
    return _dbQueue;
}


@end
